//
//  ECUIVC_CourseDetail.m
//  Edu_iOS
//
//  Created by yanyan on 2017/9/18.
//  Copyright © 2017年 yanyan. All rights reserved.
//

#import "ECUIVC_CourseDetail.h"
#import "CYUIView_Tabbar.h"
#import "CYDataHelper.h"
#import "HWHttpTool.h"
#import "UIImage+RenderedImage.h"
#import "ZFPlayerView.h"
#import "PopoverView.h"
#import "ECUShareView.h"
#import "UIView+BorderLine.h"
#import "ECFormatHelper.h"
#import "ECUIVC_CommentList.h"
#import "ECUIVC_CDetailPage.h"
#import "CourseModel.h"
#import "ECUIView_CDetailFooter.h"
#import "ECUIVC_Pay.h"
#import "ECData_Json.h"
#import "ECUCatalogModel.h"
#import "ECNewListViewController.h"
#import "Reachability.h"//网络监听
#import "XTimer.h"
#import "ECUIVC_Show.h"
#import "CYUIAlertView.h"
#import "ECUIAlertView_CourseDetail.h"
#import "ECAudioPlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import "SUPlayer.h"
#import "ECUIVC_TextViewController.h"
#define kCourseDetailFooterButtonTitleStudy @"立即学习"
#define kCourseDetailFooterButtonTitleBeMember @"加入学习"
#define kCourseDetailFooterButtonTitlePay @"立即购买"
extern  CGFloat CYTabBarViewTabOffsetInvalid;
extern NSString *CYTabIndicatorViewHeight;
extern NSString *CYTabIndicatorColor;
extern NSString *CYTabBoxBackgroundColor;
extern NSString *CYTabIndicatorCornerRadius;
const CGFloat TOPVIEW_HEIGHT = 200;    //顶部view高度

const CGFloat TABBAR_FOOTER_HEIGHT = 45;
@interface ECUIVC_CourseDetail()<UIScrollViewDelegate,CYTabbarViewDatasource,ZFPlayerDelegate,ECUCatalogControllerDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)NSURLSessionDataTask *task;

@property(nonatomic,strong)UIScrollView *scrollView;// 最底层的 scrollView
@property(nonatomic,strong)UIView *headerView;//headerView

@property(nonatomic,strong)UIImageView *videoThumbView;//视频缩略图
@property(nonatomic,strong)ZFPlayerView *videoPlayView;//视频View
@property (strong, nonatomic)UIView *playerFatherView;/** 播放器View的父视图*/
@property (nonatomic, strong) ECAudioPlayerView *audioPlayView;//音频播放器view
@property(nonatomic,strong)UIButton *videoPlayBtn;// 免费播放
@property(nonatomic,strong)UIButton *playBtn;// 播放 按钮
@property(nonatomic,strong)CYUIView_Tabbar *titleView;
@property (nonatomic, strong) ZFPlayerModel *playerModel;
@property(nonatomic,assign)BOOL isPlayed;//参考慕课，第一次进来可以滑动，之后只要点击了播放或者暂停就不让滑动了
// 三个页面
@property(nonatomic,strong)ECUIVC_CDetailPage *uivc_detail;
@property(nonatomic,strong)ECNewListViewController *uivc_catalog;
@property(nonatomic,strong)ECUIVC_CommentList *uivc_comment;
// 底部- 封装
@property(nonatomic,strong)ECUIView_CDetailFooter *footerView;
@property(nonatomic,strong)ECUIVC_Pay *uivc_pay;
@property (nonatomic, strong) CourseModel *isFavModel;//用来判断是否取消收藏
@property (nonatomic, strong) XTimer *timer;//计时器
@property (nonatomic, assign) NSInteger lookingTime;//观看时间
@property (nonatomic, copy) NSString *lessionID;
@property (nonatomic, strong) Reachability *reachability;//存储网络状态改变的
@property(nonatomic,assign)BOOL deadline;//课程是否过期 默认为 no
@property(nonatomic,strong)ECUIAlertView_CourseDetail *uiview_alert;
@property(nonatomic,strong)UIColor *navigationBarShowColor;
@end
@implementation ECUIVC_CourseDetail
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_login:) name:kNotifactionUserLogin object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:kNotifactionPaySuccess object:nil];
    _navigationBarShowColor = [[UIColor whiteColor] colorWithAlphaComponent:0];

    _isPlayed = NO;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""style:UIBarButtonItemStylePlain target:self action:nil];
    
    [self setOtherConfig];
}
- (void)paySuccess:(NSNotification *)noti
{
    // 支付完成，回到详情
    [self requestCourseDetail];

}
-(void)noti_login:(NSNotification *)noti
{
    [self requestCourseDetail];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar lt_setBackgroundColor:_navigationBarShowColor];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];

    [self setTimeConfig];
}
/* add by lizhen  -----2018年03月16日08:10:42 */
-(void)setTimeConfig{
    //初始化计时器 (统计正常观看视频的时间)
    self.timer = [XTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(XTimerSelector) userInfo:nil repeats:true];
    [self.timer stop];
    self.lookingTime = 0;
}

/* add by lizhen  -----2018年02月07日09:08:08 */
-(void)setOtherConfig{
    ///接收存在免费课时通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifactionExistFreeLesson:) name:kNotifactionExistFreeLesson object:nil];
    ///音频播放界面 播放完成 发送该通知 给"详情页" 暂停定时
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifactionAudioPlayingStatus:) name:kNotifactionAudioPlayingStatus object:nil];
    
    //DLog(@"开启 www.baidu.com 的网络检测");
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    DLog(@"-- current status: %@", reach.currentReachabilityString);
    
    // Reachability使用了通知，当网络状态发生变化时发送通知kReachabilityChangedNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appReachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    [reach startNotifier];  
}

- (void)addSubviews
{
    [super addSubviews];
    self.edgesForExtendedLayout = UIRectEdgeTop;
    [self.navigationController.navigationBar lt_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:1]];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_coursedetail_back"] style:UIBarButtonItemStylePlain target:self action:@selector(action_dismiss)];
    
    UIButton *rightBarButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 40)];
    [rightBarButton setImage:[UIImage imageNamed:@"nav_coursedetail_more"] forState:UIControlStateNormal];
    [rightBarButton addTarget:self action:@selector(action_more:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    // 这里为了滑动到顶端时 导航+状态栏+tab 那几个按钮。
    
    [self.view addSubview:self.scrollView];
    [self addChildViewControllers];
    [self.view addSubview:self.headerView];

    [self.view addSubview:self.footerView];
    self.deadline = NO;
    [self requestCourseDetail];
}

#pragma mark - 详情 -
-(void)requestCourseDetail{
    WeakSelf(weakSelf);
    CourseModel *mo = self.object;
    NSDictionary *headers = @{URL_SERVER_HEADER_USERTOKEN_KEY:[UserInfoManager shareUser].token?[UserInfoManager shareUser].token:@""};
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
   
   _task = [HWHttpTool requestWithMethod:@"GET" url:URL_CourseDetailWithId(mo.modelId) params:nil headers:headers success:^(id json) {
      
       id data = [json valueForKey:@"data"];
       [MBProgressHUD hideHUD];

       if ([[data valueForKey:@"code"] integerValue] == 500) {
           dispatch_async(dispatch_get_main_queue(), ^{
               [weakSelf showAlertControllerWithType:3];
           });
           return;
       }
        id courseData = [data valueForKey:@"course"];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.footerView.studyBtn.hidden = NO;

            weakSelf.uivc_detail.object = courseData;
            // member 标识 是否加入学习
            CourseModel *mo = weakSelf.object;
            // 系统通知里面没有 title
            mo.title = [courseData valueForKey:@"title"];
            mo.pictureUrl = [courseData valueForKey:@"middlePicture"];
            weakSelf.deadline = [[data valueForKey:@"deadline"] boolValue];
            weakSelf.uivc_catalog.deadline = weakSelf.deadline;
            NSString *status = [courseData valueForKey:@"status"];
            
            //默认 发布
            if ([CYDataHelper isNull:status]) {
                status = @"published";
            }
            mo.status = status;
            weakSelf.playBtn.hidden = YES;

            _uivc_catalog.isMember = [[data valueForKey:@"member"] integerValue];
            //发送价格和是否加入学习的状态 在目录界面判断"免费试学"是否隐藏
            if ([[data valueForKey:@"member"] integerValue] == 0) {
                mo.isMember = NO;
                //  未加入学习： 价格> 0 立即购买 == 0 立即学习； 加入学习：立即学习
                if ([[courseData valueForKey:@"price"] floatValue] > 0) {
                    [_footerView.studyBtn setTitle:kCourseDetailFooterButtonTitlePay forState:UIControlStateNormal];
                } else {
                    [_footerView.studyBtn setTitle:kCourseDetailFooterButtonTitleBeMember forState:UIControlStateNormal];
                }
            } else {
//                [_videoPlayBtn setHidden:YES];
                mo.isMember = YES;
                if (self.deadline) {
                    if ([[courseData valueForKey:@"price"] floatValue] > 0) {
                        [_footerView.studyBtn setTitle:kCourseDetailFooterButtonTitlePay forState:UIControlStateNormal];
                    } else {
                        [_footerView.studyBtn setTitle:kCourseDetailFooterButtonTitleBeMember forState:UIControlStateNormal];
                    }
                } else {
                //  用户加入课程显示在目录
                [weakSelf showCatalog];
                [_footerView.studyBtn setTitle:kCourseDetailFooterButtonTitleStudy forState:UIControlStateNormal];
                 weakSelf.playBtn.hidden = NO;
                [weakSelf hiddenFooterView:YES];
                }
            }
            [_videoThumbView sd_setImageWithURL:[NSURL URLWithString:[courseData valueForKey:@"middlePicture"]] placeholderImage: [UIImage imageNamed:kEduCourseImagePlaceholderName]];
            //  收藏
            BOOL isFavorited = [[data valueForKey:@"hasFavorited"] boolValue];
            mo.isFavorited = isFavorited;
            NSString *price = [courseData valueForKey:@"price"];
            mo.price = [courseData valueForKey:@"price"];

            NSString *originPrice = [courseData valueForKey:@"originPrice"];
            if ([price floatValue] <= [originPrice floatValue]) {
                _footerView.promotionPriceLabel.attributedText = [ECFormatHelper attributedStringForPromotionPrice:price decimal:2 smallFontSize:14];
                _footerView.originPriceLabel.attributedText = nil;
            } else {
                _footerView.promotionPriceLabel.attributedText = [ECFormatHelper attributedStringForPromotionPrice:price decimal:2 smallFontSize:14];
                _footerView.originPriceLabel.attributedText = nil;
            }
            if (mo.isMember && self.deadline) {
                // 课程加入学习，课程已过期，都给出提示
                if ([status isEqualToString:@"closed"]) {
                    //您购买的课程已到期且已关闭，无法重新购买学习。 点击确定返回上一界面
                    [weakSelf showAlertControllerWithType:1];
                } else {
                    if ([mo.price floatValue] <= 0) {
                        [weakSelf showAlertControllerWithType:4];
                    } else {
                        [weakSelf showAlertControllerWithType:2];
                    }
                }
                // 显示footer
                [weakSelf hiddenFooterView:NO];

                return;
            }

            if ([mo.status isEqualToString:@"closed"] && !mo.isMember && [UserInfoManager shareUser].token) {
               // 课程未加入，课程关闭
                [weakSelf showAlertControllerWithType:0];
                [weakSelf hiddenFooterView:NO];
                return;
            }


        });
       
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showInfoMessage:@"课程详情请求失败"];
        [weakSelf hiddenFooterView:YES];
//        weakSelf.footerView.studyBtn.hidden = YES;

    }];
    
}
- (void)hiddenFooterView:(BOOL)isHide
{
    self.footerView.hidden = isHide;

    if (isHide) {
        self.scrollView.height = kScreenHeight -  kNavHeight - TABBAR_TITLE_HEIGHT;
        _uivc_detail.view.height = _uivc_comment.view.height = _uivc_catalog.view.height = kScreenHeight -  kNavHeight - TABBAR_TITLE_HEIGHT;

    } else {
        self.scrollView.height = kScreenHeight -  kNavHeight - TABBAR_TITLE_HEIGHT - TABBAR_FOOTER_HEIGHT;
        _uivc_detail.view.height = _uivc_comment.view.height = _uivc_catalog.view.height = kScreenHeight -  kNavHeight - TABBAR_TITLE_HEIGHT - TABBAR_FOOTER_HEIGHT;
    }
    _scrollView.contentSize = CGSizeMake(3 * kScreenWidth, _scrollView.frame.size.height);

}
-(void)showAlertControllerWithType:(NSInteger)type
{
    NSMutableAttributedString *attributeString;
    NSString *confirmTitle = nil;
    NSString *cancleTitle = @"确定";

    if (type == 0) {
        //已关闭 没有购买或者加入，但在订单里面
        attributeString = [[NSMutableAttributedString alloc]initWithString:@"抱歉，课程已关闭无法进行购买学习。如有疑问请咨询客服。" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];

    } else if (type == 1) {
        //已到期且已关闭
        attributeString = [[NSMutableAttributedString alloc]initWithString:@"您购买的课程已到期且已关闭，无法重新购买学习" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];

    } else if (type == 2) {
        confirmTitle = @"立即购买";
        cancleTitle = @"取消";
        attributeString = [[NSMutableAttributedString alloc]initWithString:@"您购买的课程已到期，无法再继续学习\n" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];
        NSMutableAttributedString *title2 = [[NSMutableAttributedString alloc]initWithString:@"如有疑问请联系老师或重新购买课程"];
        [title2 addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithRed:0.5882 green:0.5882 blue:0.5882 alpha:1]} range:NSMakeRange(0, 10)];
        [title2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(10, 6)];
        [title2 addAttribute:NSForegroundColorAttributeName value:ECTHEMESELECTEDCOLOR range:NSMakeRange(10, 6)];
        [attributeString appendAttributedString:title2];
        


    } else if (type == 3) {
        // 课程删除
        attributeString = [[NSMutableAttributedString alloc]initWithString:kAlertTipOfCourseDelete attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];

    } else if(type == 4) {
        // 这是免费的课程 到期
        confirmTitle = @"加入学习";
        cancleTitle = @"取消";
        attributeString = [[NSMutableAttributedString alloc]initWithString:@"您购买的课程已到期，无法再继续学习\n" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];
        NSMutableAttributedString *title2 = [[NSMutableAttributedString alloc]initWithString:@"如有疑问请联系老师或重新购买课程"];
        [title2 addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithRed:0.5882 green:0.5882 blue:0.5882 alpha:1]} range:NSMakeRange(0, 10)];
        [title2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(10, 6)];
        [title2 addAttribute:NSForegroundColorAttributeName value:ECTHEMESELECTEDCOLOR range:NSMakeRange(10, 6)];
        [attributeString appendAttributedString:title2];
    }
        
    _uiview_alert = [[ECUIAlertView_CourseDetail alloc]initWithTitle:attributeString cancleTitle:cancleTitle confirmTitle: confirmTitle];
    [_uiview_alert showAlert];
    WeakSelf(weakSelf);
    _uiview_alert.block_cancel = ^(){
        if (confirmTitle) {
            return;
        } else {
        [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
    _uiview_alert.block_confirm = ^(){
        CourseModel *mo = weakSelf.object;
        if ([mo.price floatValue] <= 0 ) {
            // 加入学习
            [weakSelf becomeCourseMember:mo.modelId];
        } else  {
            // 重新购买课程 - 生成订单号
            [weakSelf generateOrderSnVC:nil];
        }
        
    };
}
-(void)action_dismiss{
    //self.lookingTime = 0;
    [self.navigationController popViewControllerAnimated:YES];
    //判断播放器对象是否初始化
    if (_videoPlayView){
        [self.videoPlayView resetPlayer];//释放播放器
    }
    if (_audioPlayView) {
        [_audioPlayView removeAudioPlayer];
        _audioPlayView = nil;
    }
    
}
-(void)action_more:(UIButton *)item{
    
    PopoverView *popoverView = [PopoverView popoverView];
    popoverView.showShade = YES; // 显示阴影背景
    popoverView.arrowStyle = PopoverViewArrowStyleTriangle;
    [popoverView showToView:item withActions:[self Actions]];
    
}
-(UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kNavHeight + TABBAR_TITLE_HEIGHT, kScreenWidth, kScreenHeight -  kNavHeight - TABBAR_TITLE_HEIGHT - TABBAR_FOOTER_HEIGHT)];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
//        _scrollView.bounces = YES;
//        _scrollView.exclusiveTouch = YES;
        _scrollView.contentSize = CGSizeMake(3 * kScreenWidth, _scrollView.frame.size.height);
    }
    return _scrollView;
}
-(UIView *)headerView
{
    if (!_headerView) {
        //headerView
        WeakSelf(weakSelf);
        
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, HEADERVIEW_HEIGHT)];
        _videoThumbView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"logo_login"]];
        _videoThumbView.frame = CGRectMake(0, 0, CGRectGetWidth(_headerView.bounds), CGRectGetWidth(_headerView.bounds) * 0.5625);

        _videoThumbView.userInteractionEnabled = YES;
        [_headerView addSubview:_videoThumbView];
        //button
        _videoPlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_videoPlayBtn setBackgroundImage:[UIImage imageNamed:@"detail_freeStudy"] forState:UIControlStateNormal];
        CGFloat btnWidth = 96 * kPercentage;
        _videoPlayBtn.frame = CGRectMake(kScreenWidth/2 - btnWidth/2, CGRectGetHeight(_videoThumbView.frame)/2 - btnWidth * 0.2, btnWidth, btnWidth * 0.4);
        [_videoPlayBtn addTarget:self action:@selector(action_play:) forControlEvents:UIControlEventTouchUpInside];
        [_videoThumbView addSubview:_videoPlayBtn];
        [_videoPlayBtn setHidden:YES];
        //播放按钮

        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat playWidth = 45;
        [_playBtn setBackgroundImage:[UIImage imageNamed:@"detail_play"] forState:UIControlStateNormal];
        _playBtn.frame = CGRectMake(kScreenWidth/2 - playWidth/2, CGRectGetHeight(_videoThumbView.frame)/2 - playWidth * 0.5, playWidth, playWidth);
        [_playBtn addTarget:self action:@selector(action_pay:) forControlEvents:UIControlEventTouchUpInside];
        [_videoThumbView addSubview:_playBtn];
        [_playBtn setHidden:YES];
        // titleView
        _titleView = [[CYUIView_Tabbar alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_videoThumbView.frame), kScreenWidth, TABBAR_TITLE_HEIGHT - 3)];
        _titleView.backgroundColor = [UIColor whiteColor];
        _titleView.indicatorAttributes = @{CYTabIndicatorColor:ECTHEMESELECTEDCOLOR,CYTabIndicatorViewHeight:@(2.0f * kPercentage),CYTabBoxBackgroundColor:ECTHEMESELECTEDCOLOR,CYTabIndicatorCornerRadius:@(kPercentage)};
        _titleView.selectedAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13.0f * kPercentage],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#ff6700"]};
        _titleView.selectionType = CYTabbarSelectionIndicator;
        _titleView.needTextGradient = NO;
        _titleView.scrollEnable = NO;
        _titleView.dataSource = self;
        _titleView.indicatorEqualTitleWidth = YES;
        _titleView.block_IndexPathSelected = ^(NSIndexPath * _Nonnull indexPath) {
            [weakSelf.scrollView setContentOffset:CGPointMake(kScreenWidth*indexPath.row, 0) animated:YES];
            [weakSelf reloadMaxOffsetY];
        };
        [_headerView addSubview:_titleView];
        //  分割线
        UIView *line1View = [[UIView alloc]initWithFrame:CGRectMake((kScreenWidth - 2 )/ 3.0, 10, 1, 20)];
        line1View.backgroundColor = [UIColor colorWithRed:0.9255 green:0.9255 blue:0.9255 alpha:1];
        [_titleView addSubview:line1View];
        UIView *line2View = [[UIView alloc]initWithFrame:CGRectMake((kScreenWidth - 2) / 3.0 * 2 + 1, CGRectGetMinY(line1View.frame), CGRectGetWidth(line1View.frame), CGRectGetHeight(line1View.frame))];
        line2View.backgroundColor = [UIColor colorWithRed:0.9255 green:0.9255 blue:0.9255 alpha:1];
        [_titleView addSubview:line2View];
        _headerView.backgroundColor = [UIColor whiteColor];
//        [_headerView inBorderForColor:[UIColor colorWithHexString:@"#f2f5f6"] borderWidth:3 borderType:UIBorderSideTypeBottom];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleView.frame), kScreenWidth, 3)];
        view.backgroundColor = [UIColor colorWithHexString:@"#f2f5f6"];
        [_headerView addSubview:view];
    }
    return _headerView;
}

-(UIView *)playerFatherView{
    if (!_playerFatherView) {
        _playerFatherView = [[UIView alloc] initWithFrame:_videoThumbView.bounds];
        [_videoThumbView addSubview:_playerFatherView];
    }
    return _playerFatherView;
}

-(ZFPlayerView *)videoPlayView{
    if (!_videoPlayView) {
            _videoPlayView = [[ZFPlayerView alloc] init];
            //自定义view 传入nil则默认
            [_videoPlayView playerControlView:nil playerModel:self.playerModel];
            // 设置代理
            _videoPlayView.delegate = self;
            
            ///kvo 监听播放器state状态变化
            [_videoPlayView addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _videoPlayView;
}

-(ECAudioPlayerView *)audioPlayView{
    if (!_audioPlayView) {
        _audioPlayView = [[ECAudioPlayerView alloc]init];
        _audioPlayView.frame = _videoThumbView.bounds;
        [_videoThumbView addSubview:_audioPlayView];
        
        ///kvo 监听播放器state状态变化
        //[_audioPlayView.player addObserver:self forKeyPath:@"status_audio" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _audioPlayView;
}

-(void)audioPlaybackFinished{
    [self.timer stop];
}

- (ECUIView_CDetailFooter *)footerView
{
    if (!_footerView) {
        _footerView = [[ECUIView_CDetailFooter alloc]initWithFrame:CGRectMake(0, kScreenHeight - TABBAR_FOOTER_HEIGHT, kScreenWidth, TABBAR_FOOTER_HEIGHT)];
        [_footerView borderForColor:[UIColor colorWithHexString:@"#c1c1c1"] borderWidth:0.5 borderType:UIBorderSideTypeTop];
        [_footerView setBackgroundColor:[UIColor colorWithHexString:@"#fcfcfc"]];
        WeakSelf(weakSelf);
        
        _footerView.block_selected = ^(id obj) {
            [weakSelf action_pay:obj];
        };
    }
   
    return  _footerView;
}

#pragma mark - 立即学习，加入学习，立即购买 -
- (void)action_pay:(id)sender
{
    CourseModel *mo = self.object;
    
    if (mo.isMember) {
        // 继续学习
        //  这里是因为有 dealine 失效
        if ([[_footerView.studyBtn titleForState:UIControlStateNormal]  isEqualToString:kCourseDetailFooterButtonTitlePay]) {
            [self generateOrderSnVC:sender];
            return;
        } else if ([[_footerView.studyBtn titleForState:UIControlStateNormal]  isEqualToString:kCourseDetailFooterButtonTitleBeMember]){
            [self becomeCourseMember:mo.modelId];
            return;
        }
        // 如果点击立即学习,展示目录
        [self showCatalog];
        [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionUserGoToLearn object:nil];
    } else {
        if (![[UserInfoManager shareUser] token]) {
// 直接跳转登录页面
            [ECUIVC_Show isShowLoginVCAtViewController:self];
            return;
        }
//        if([mo.status isEqualToString:@"closed"] && !mo.isMember ){
//            //已关闭 没有购买或者未加入，但在订单里面
//            [self showAlertControllerWithType:0];
//            return;
//
//        } else if(self.deadline && mo.isMember){
//            [self showAlertControllerWithType:2];
//
//        }
        if ([mo.price floatValue] <= 0 ) {
            // 加入学习
            [self becomeCourseMember:mo.modelId];
        } else  {
            // 购买课程 - 生成订单号
            [self generateOrderSnVC:sender];
        }
      
    }

}
- (void)showCatalog{
    if (self.titleView.selectedIndex != 1){
        
        [_titleView setTabIndex:1 animated:YES];
        [_scrollView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
    }
}
#pragma mark - 购买课程 -
-(void)generateOrderSnVC:(id)sender
{
    _uivc_pay = [[ECUIVC_Pay alloc]init];
    _uivc_pay.isFromCourseDetail = YES;
    _uivc_pay.object = self.object;
    [self.navigationController pushViewController:_uivc_pay animated:YES];
}
-(void)becomeCourseMember:(id)sender
{
    CourseModel *mo = self.object;
    WeakSelf(weakSelf);
    [HWHttpTool requestWithMethod:@"POST" url:URL_CourseMemberWithId(mo.modelId) params:nil headers:@{URL_SERVER_HEADER_USERTOKEN_KEY:[UserInfoManager shareUser].token} success:^(id json) {
        [MBProgressHUD showInfoMessage:@"成功加入学习"];
        [_footerView.studyBtn setTitle:@"立即学习" forState:UIControlStateNormal];

         CourseModel *mo = weakSelf.object;
        mo.isMember = YES;
        [_videoPlayBtn setHidden:YES];
//         加入学习成功
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotifactionUserAddOrBuyLearn object:@(YES)];
    } failure:^(NSError *error) {
       
        if ([ECData_Json tokenFailureForRequestError:error]) {
            // 用户 token 失效
            [MBProgressHUD showInfoMessage:@"用户信息已失效，请重新登录"];
        } else {
            [MBProgressHUD showInfoMessage:@"用户加入学习失败"];

        }
    }];
}
- (void)action_play:(id)sender{
    [self startPlayVedio];
    [self showCatalog];
    [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionUserGoToLearn object:nil];
    
}
- (void)startPlayVedio
{
    if (!_isPlayed) {
        [self setNavigationBarColorWithOffsetY:0];
    }
    _isPlayed = YES;
    self.scrollView.directionalLockEnabled = YES;
//    self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, 0);
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return  YES;
}
////是否支持旋转屏幕
- (BOOL)shouldAutorotate{
    return NO;
}
- (ZFPlayerModel *)playerModel{
    if (!_playerModel) {
        _playerModel                  = [[ZFPlayerModel alloc] init];
        _playerModel.placeholderImage = [UIImage imageNamed:@"logo_login"];
        _playerModel.fatherView       = self.playerFatherView;
        
    }
    return _playerModel;
}
#pragma  mark - ZF Delegate -

- (void)zf_playerBackAction{
    [self.videoPlayView resetPlayer];
    [self.videoPlayView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma  mark - add VCs -
- (void)addChildViewControllers{
    WeakSelf(weakSelf);
    // 详情
    _uivc_detail = [[ECUIVC_CDetailPage alloc]init];
    [self addChildViewController:_uivc_detail];
//    _uivc_detail.tableView.canCancelContentTouches = NO;
//    _uivc_detail.tableView.delaysContentTouches = YES;
    [_uivc_detail tableViewDidScroll:^(CGFloat contentOffsetY) {
        [weakSelf setNavigationBarColorWithOffsetY:contentOffsetY];
        
    }];
    _uivc_detail.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavHeight-TABBAR_TITLE_HEIGHT);
    [_scrollView addSubview:_uivc_detail.view];
    
    //目录
    _uivc_catalog = [[ECNewListViewController alloc]init];
    _uivc_catalog.delegate = self;
    CourseModel *courseModel = self.object;//获取页面courseId
    _uivc_catalog.courseModel = courseModel;//给目录界面传值
    //_uivc_catalog.deadline = self.deadline;
    _uivc_catalog.view.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight-kNavHeight-TABBAR_TITLE_HEIGHT);

    [self addChildViewController:_uivc_catalog];
    [_uivc_catalog tableViewDidScroll:^(CGFloat contentOffsetY) {
        [weakSelf setNavigationBarColorWithOffsetY:contentOffsetY];
        
    }];
    [_scrollView addSubview:_uivc_catalog.view];
    
    //评论
    _uivc_comment = [[ECUIVC_CommentList alloc]init];
    _uivc_comment.object = self.object;
//    _uivc_comment.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavHeight - TABBAR_FOOTER_HEIGHT);
    _uivc_comment.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavHeight - TABBAR_TITLE_HEIGHT);
    [self addChildViewController:_uivc_comment];
    
    [_uivc_comment tableViewDidScroll:^(CGFloat contentOffsetY) {
        [weakSelf setNavigationBarColorWithOffsetY:contentOffsetY];
        
    }];
    _uivc_comment.view.frame = CGRectMake(kScreenWidth * 2, 0, kScreenWidth, kScreenHeight-kNavHeight-TABBAR_TITLE_HEIGHT);
    [_scrollView addSubview:_uivc_comment.view];
    
}
//  根据偏移量设置导航
- (void)setNavigationBarColorWithOffsetY:(CGFloat )offsetY
{
    
    UIColor *color = [UIColor colorWithHex:0xe3e3e3];
    CGFloat alpha = 0;
    if (!self.isPlayed && offsetY > 0) {
            alpha = offsetY/TABLEVIEWCONTENT_OFFSET_Y;
            alpha = MIN(offsetY/TABLEVIEWCONTENT_OFFSET_Y, 1);
            CourseModel *mo = self.object;
            self.navigationItem.title = mo.title;
        } else {
            self.navigationItem.title = @"";
        }
      
   
    _navigationBarShowColor = [color colorWithAlphaComponent:alpha];
    [self.navigationController.navigationBar lt_setBackgroundColor:_navigationBarShowColor];
    self.navigationController.navigationBar.shadowImage = [UIImage imageWithColor:[[UIColor  darkGrayColor] colorWithAlphaComponent:alpha] renderSize:CGSizeMake(kScreenWidth, 0.25)];
    if (self.isPlayed) {
        return;
    }
    [self setHeaderViewFrame:offsetY];
}
- (void)setHeaderViewFrame:(CGFloat)contentOffsetY {
    if (contentOffsetY < TABLEVIEWCONTENT_OFFSET_Y) {
        
        _uivc_detail.tableView.contentOffset = CGPointMake(0, contentOffsetY);
        _uivc_catalog.tableView.contentOffset = CGPointMake(0, contentOffsetY);
        _uivc_comment.tableView.contentOffset = CGPointMake(0, contentOffsetY);
        if ([_uivc_detail.tableView isFirstResponder]) {
            _uivc_detail.tableView.contentOffset = CGPointMake(0, TABLEVIEWCONTENT_OFFSET_Y);

        }
        CGRect frame = self.headerView.frame;
        frame.origin.y = -contentOffsetY;
        if (contentOffsetY <= 0) {
            frame.origin.y = 0;
        }
        frame.origin.y = 0;
        
        self.headerView.frame = frame;
        
    } else {
        CGRect frame = self.headerView.frame;
        frame.origin.y = -TABLEVIEWCONTENT_OFFSET_Y;
        self.headerView.frame = frame;
    }
    
}

- (NSArray<NSString *> *)tabbarTitlesForTabbarView:(CYUIView_Tabbar *)tabbarView
{
    return @[@"详情",@"目录",@"评价"];
}
#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_titleView setTabbarOffsetX:(scrollView.contentOffset.x)/self.view.bounds.size.width];
    
}
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    [self scrollViewDidEndScrollingAnimation:scrollView];
//}
//- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
//    NSInteger index = scrollView.contentOffset.x/kScreenWidth;
//    CYUIVC_base *page = self.childViewControllers[index];
//    if (page.view.superview) {
//        return;
//    }
//    page.view.frame = CGRectMake(kScreenWidth*index, 0, kScreenWidth, kScreenHeight-kNavHeight-TABBAR_TITLE_HEIGHT);
//    [_scrollView addSubview:page.view];
//}

//拖拽scrollView时刷新tableView偏移量
//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    [self reloadMaxOffsetY];
//}
/**
 * 找出子controller偏移量最大的tableView
 * 如果其偏移量大于tableViewContentOffsetY
 * 再找出偏移量小于tableViewContentOffsetY的tableView
 * 让偏移量等于tableViewContentOffsetY
 *
 */
- (void)reloadMaxOffsetY{
    CGFloat maxY = 0;
    //  取三个页面的最大偏移量
    for (CYUIVC_base *page in self.childViewControllers) {
        if ([page isKindOfClass:[ECUIVC_CDetailPage class]]) {
            if (_uivc_detail.tableView.contentOffset.y > maxY) {
                maxY = ((ECUIVC_Material *)page).tableView.contentOffset.y;
            }
        }
        if ([page isKindOfClass:[ECNewListViewController class]]) {
            if ( ((ECNewListViewController *)page).tableView.contentOffset.y > maxY) {
                maxY = ((ECNewListViewController *)page).tableView.contentOffset.y;
            }
        }
//        if ([page isKindOfClass:[ECUIVC_CommentList class]]) {
//            if ( ((ECUIVC_CommentList *)page).tableView.contentOffset.y > maxY) {
//                maxY = ((ECUIVC_CommentList *)page).tableView.contentOffset.y;
//            }
//        }
    }
    
    if (maxY > TABLEVIEWCONTENT_OFFSET_Y) {
        for (CYUIVC_base *page in self.childViewControllers) {
            if ([page isKindOfClass:[ECUIVC_CDetailPage class]]) {
                if (((ECUIVC_CDetailPage *)page).tableView.contentOffset.y < TABLEVIEWCONTENT_OFFSET_Y) {
                    ((ECUIVC_CDetailPage *)page).tableView.contentOffset = CGPointMake(0, TABLEVIEWCONTENT_OFFSET_Y);
                }
            }
            if ([page isKindOfClass:[ECNewListViewController class]]) {
                if (((ECNewListViewController *)page).tableView.contentOffset.y < TABLEVIEWCONTENT_OFFSET_Y) {
                    ((ECNewListViewController *)page).tableView.contentOffset = CGPointMake(0, TABLEVIEWCONTENT_OFFSET_Y);
                }
            }
        }
        
    }
    
}

#pragma mark 右上角子菜单
- (NSArray<PopoverAction *> *)Actions{
    WeakSelf(weakSelf);
    self.isFavModel = self.object;
    
    NSString *favImageStr = self.isFavModel.isFavorited == 0 ? @"pop_star" : @"pop_cancelStar";
    NSString *favTitleStr = self.isFavModel.isFavorited == 0 ? @"收藏" : @"已收藏";
    //收藏栏
    PopoverAction *favAction = [PopoverAction actionWithImage:[UIImage imageNamed:favImageStr] title:favTitleStr handler:^(PopoverAction *action) {
        if (![[UserInfoManager shareUser] token]) {
            // 直接跳转登录页面
            [ECUIVC_Show isShowLoginVCAtViewController:weakSelf];
            return;
        }
        if (weakSelf.isFavModel.isFavorited == 0) {
            [weakSelf loadFavroiteData];
        }else{
            [weakSelf loadCancelFavroiteData];
        }
    }];
    
    // 分享 action
    PopoverAction *shareAction = [PopoverAction actionWithImage:[UIImage imageNamed:@"pop_share"] title:@"分享" handler:^(PopoverAction *action) {
        DLog(@"分享");

        ECUShareView *vc = [[ECUShareView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        CourseModel *mo = self.object;
        vc.title_course = mo.title;
        vc.icon_course = mo.pictureUrl;
        [[UIApplication sharedApplication].keyWindow addSubview:vc];
    }];
    
    return @[favAction, shareAction];
}

#pragma mark 点击cell传值delegate
- (void)didSelectOfCellWithPaperModel:(ECListModel *)model
{
    if (_videoPlayView != nil) {
        [_videoPlayView pause];
    }
    if (_audioPlayView != nil) {
        [_audioPlayView.player pause];
    }
    ECUIVC_TextViewController *vc = [[ECUIVC_TextViewController alloc]init];
    vc.foldCellModel = model;
    vc.title = model.title;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)didSelectOfCellWithModel:(ECListModel *)model{
    
    _lessionID = model.data.ID;
    [self showCatalog];
    if (self.reachability.isReachableViaWWAN) {//先判断网络状态
        int isButtonOn = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchButtonStatus"] intValue];
        if (isButtonOn == 1) {
            [MBProgressHUD showTipMessageInWindow:@"正在使用移动网络播放"];
            [self playMediaModel:model];
        } else {
            [MBProgressHUD showTipMessageInWindow:@"若允许移动网络下播放，请在“设置”中打开"];
        }
    } else if (self.reachability.isReachableViaWiFi) {//若为WiFi状态下,直接播放
        [self playMediaModel:model];
    }
}

- (void)playMediaModel:(ECListModel *)model
{
    if ([model.type isEqualToString:@"video"]) {
        if (_audioPlayView != nil) {
            [_audioPlayView removeFromSuperview];
            _audioPlayView = nil;
        }
        
        self.playerModel.title = model.title;
        self.playerModel.videoURL = [NSURL URLWithString:model.data.media];
        [self.videoPlayView resetToPlayNewVideo:self.playerModel];
    } else if ([model.type isEqualToString:@"audio"]){
        if (_videoPlayView != nil) {
            [_videoPlayView removeFromSuperview];
            _videoPlayView = nil;
        }
        [self.audioPlayView setUrlOfAudioPlayView:model.data.media];
    }
    self.lookingTime = 0;
    [self startPlayVedio];
    [self.timer reStart];
}
#pragma mark 是否存在免费课时通知 add by lz
-(void)notifactionExistFreeLesson:(NSNotification *)noti{
    //接受通知 隐藏免费试听按钮
    WeakSelf(weakSelf);
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        if ([noti.userInfo[@"isShowFreeLearnImage"] isEqualToString:@"yes"]) {
            [weakSelf.videoPlayBtn setHidden:NO];
            if (!weakSelf.playBtn.hidden) {
                [weakSelf.videoPlayBtn setHidden:YES];
            }
        }else{
            [weakSelf.videoPlayBtn setHidden:YES];
        }
    });
}

#pragma mark 网络监听通知 add by lz
- (void) appReachabilityChanged:(NSNotification*)note {
    self.reachability = [note object];
    
    if(![self.reachability isReachable]){
        return;
    }
    
    if (self.reachability.isReachableViaWiFi) {
        DLog(@"wifi");
        return;
    }
    
    if (self.reachability.isReachableViaWWAN) {
        if (_videoPlayView == nil) {
            return;
        }
        //在播放/加载过程中 网络状态变化后的操作
        if (self.videoPlayView.state == ZFPlayerStatePlaying || self.videoPlayView.state == ZFPlayerStateBuffering) {
            int isButtonOn = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchButtonStatus"] intValue];
            if (isButtonOn == 1) {
                [MBProgressHUD showTipMessageInWindow:@"您正在使用蜂窝数据观看视频"];
            }else{
                [self.videoPlayView pause];
                [MBProgressHUD showTipMessageInWindow:@"若允许使用数据观看视频,请去'我的'-'设置'界面前去允许"];
            }
        }
    }
}

/*
 收藏接口
 */
-(void)loadFavroiteData{
    WeakSelf(weakSelf);
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_Favroite(self.isFavModel.modelId)
                           params:nil
                          headers: @{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              weakSelf.isFavModel.isFavorited = 1;
                              [MBProgressHUD showTipMessageInWindow:@"收藏成功"];
                              
                          }
                          failure:^(NSError *error) {
                              [MBProgressHUD showTipMessageInWindow:@"收藏失败"];
                          }];
}

/*
 取消收藏接口
 */
-(void)loadCancelFavroiteData{
    WeakSelf(weakSelf);
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_CancelFavroite
                           params:@{@"ids":self.isFavModel.modelId}
                          headers: @{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              weakSelf.isFavModel.isFavorited = 0;
                              [MBProgressHUD showTipMessageInWindow:@"取消成功"];
                          }
                          failure:^(NSError *error) {
                              [MBProgressHUD showTipMessageInWindow:@"取消失败"];
                          }];
}

/*
 kvo   add by lz
 
 ZFPlayerStateFailed,     0// 播放失败
 ZFPlayerStateBuffering,  1// 缓冲中
 ZFPlayerStatePlaying,    2// 播放中
 ZFPlayerStateStopped,    3// 停止播放
 ZFPlayerStatePause       4// 暂停播放
 
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {//视频走该回调 视频监听state
    if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 0) {
    }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 5) {//播放失败
        [self.timer stop];
    }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 1 || [[change valueForKey:NSKeyValueChangeNewKey]intValue] == 4) {
        //[self.timer stop];
    }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 2){
        //[self.timer reStart];
    }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 3){
        [self.timer stop];
    } else{
        
    }
}

/**
 SUPlayerStateWaiting,
 SUPlayerStatePlaying,
 SUPlayerStatePaused,
 SUPlayerStateStopped,
 SUPlayerStateBuffering,
 SUPlayerStateError
 */
///音频播放界面 播放完成 发送该通知 给"详情页" 暂停定时器
-(void)notifactionAudioPlayingStatus:(NSNotification *)noti{
    int status_audio = [noti.userInfo[@"status_audio"] intValue];
    if (status_audio == 5 || status_audio == 3) {
        [self.timer stop];
    }
}

-(void)XTimerSelector{
    self.lookingTime ++;
    DLog(@"%ld",self.lookingTime);
}

//发送学习时长
-(void)sendLearningTime{
    if (![[UserInfoManager shareUser] token] || [[UserInfoManager shareUser] token].length <= 0) {
        DLog(@"用户没有登录");
        return;
    }
    NSString *str = URL_POST_CourseDetailTimeWith(self.lessionID);
    NSString *url = [NSString stringWithFormat:@"%@/%ld",str,self.lookingTime];//拼接参数
    NSString *token = [[UserInfoManager shareUser] token]?[[UserInfoManager shareUser] token]:@"";
    [HWHttpTool requestWithMethod:@"POST"
                              url:url
                           params:nil
                          headers:@{@"X-AUTH-TOKEN":token}
                          success:^(id json) {
                              DLog(@"发送时长----%@",json);
                          }
                          failure:^(NSError *error) {
                          }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.lookingTime > 10) {
        [self sendLearningTime];//大于60秒 发送学习时间
    }
    [self.timer invalidate];//废除计时器
    
    if (!_audioPlayView){
        [_audioPlayView removeAudioPlayer];
        [_audioPlayView removeFromSuperview];
        _audioPlayView = nil;
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

    DLog(@"dealloc.... %@",self.class);
    //判断播放器对象是否初始化
    if (_videoPlayView != NULL){
        [self.videoPlayView resetPlayer];//释放播放器
        [self.videoPlayView removeObserver:self forKeyPath:@"state"];
    }
}
@end
